package com.hnguigu.tms.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnguigu.tms.order.DTO.OrderDTO;
import com.hnguigu.tms.order.DTO.OrderSearchDTO;
import com.hnguigu.tms.order.entity.Areas;
import com.hnguigu.tms.order.entity.Cities;
import com.hnguigu.tms.order.entity.Order;
import com.hnguigu.tms.order.entity.Provinces;
import com.hnguigu.tms.order.entity.fact.AddressCheckResult;
import com.hnguigu.tms.order.entity.fact.AddressRule;
import com.hnguigu.tms.order.mapper.AreasMapper;
import com.hnguigu.tms.order.mapper.CitiesMapper;
import com.hnguigu.tms.order.mapper.OrderMapper;
import com.hnguigu.tms.order.mapper.ProvincesMapper;
import com.hnguigu.tms.order.service.IOrderService;
import com.hnguigu.tms.util.*;
import org.apache.commons.lang.StringUtils;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务实现类
 */
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private IdWorker idGenerator;
    @Autowired
    private OrderMapper orderMapper;

//    @Autowired
//    private KieContainer kieContainer;

    /**
     * 新增订单
     *
     * @param order 订单信息
     * @return
     */
    @Override
    public Order saveOrder(Order order) {

        //判断是否为同城
        System.out.println("------------------------------------ ----------------------------------- --------------");
        System.out.println(order.getReceiverCityId()+","+order.getSenderCityId());
        if(order.getReceiverCityId().equals(order.getSenderCityId())){
            System.out.println("订单为同城订单");
            order.setOrderType(1);
            order.setPickupType(1);
        }else{
            System.out.println("订单为城际订单");
            order.setOrderType(2);
            order.setPickupType(2);
        }
        order.setOrderId(Long.toString(idGenerator.nextId()));
        order.setCreateTime(LocalDateTime.now());
        order.setPaymentStatus(OrderPaymentStatus.UNPAID.getStatus());
        if (OrderPickupType.NO_PICKUP.getCode() == order.getPickupType()) {
            order.setStatus(OrderStatus.OUTLETS_SINCE_SENT.getCode());
        } else {
            order.setStatus(OrderStatus.PENDING.getCode());
        }
        save(order);

        return order;
    }

    /**
     * 获取订单分页数据
     *
     * @param page     页码
     * @param pageSize 页尺寸
     * @param order    查询条件
     * @return
     */
    @Override
    public IPage<Order> findByPage(Integer page, Integer pageSize, Order order) {
//        if(page==null){
//            page=1;
//        }
//        if(pageSize==null){
//            pageSize=10;
//        }
        Page<Order> iPage = new Page(page, pageSize);
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(order.getOrderId())) {
            lambdaQueryWrapper.like(Order::getOrderId, order.getOrderId());
        }
        if (order.getStatus() != null) {
            lambdaQueryWrapper.eq(Order::getStatus, order.getStatus());
        }
        if (order.getPaymentStatus() != null) {
            lambdaQueryWrapper.eq(Order::getPaymentStatus, order.getPaymentStatus());
        }
        //发件人信息
        if (StringUtils.isNotEmpty(order.getSenderName())) {
            lambdaQueryWrapper.like(Order::getSenderName, order.getSenderName());
        }
        if (StringUtils.isNotEmpty(order.getSenderPhone())) {
            lambdaQueryWrapper.like(Order::getSenderPhone, order.getSenderPhone());
        }
        if (StringUtils.isNotEmpty(order.getSenderProvinceId())) {
            lambdaQueryWrapper.eq(Order::getSenderProvinceId, order.getSenderProvinceId());
        }
        if (StringUtils.isNotEmpty(order.getSenderCityId())) {
            lambdaQueryWrapper.eq(Order::getSenderCityId, order.getSenderCityId());
        }
        if (StringUtils.isNotEmpty(order.getSenderCountyId())) {
            lambdaQueryWrapper.eq(Order::getSenderCountyId, order.getSenderCountyId());
        }
        //收件人信息
        if (StringUtils.isNotEmpty(order.getReceiverName())) {
            lambdaQueryWrapper.like(Order::getReceiverName, order.getReceiverName());
        }
        if (StringUtils.isNotEmpty(order.getReceiverPhone())) {
            lambdaQueryWrapper.like(Order::getReceiverPhone, order.getReceiverPhone());
        }
        if (StringUtils.isNotEmpty(order.getReceiverProvinceId())) {
            lambdaQueryWrapper.eq(Order::getReceiverProvinceId, order.getReceiverProvinceId());
        }
        if (StringUtils.isNotEmpty(order.getReceiverCityId())) {
            lambdaQueryWrapper.eq(Order::getReceiverCityId, order.getReceiverCityId());
        }
        if (StringUtils.isNotEmpty(order.getReceiverCountyId())) {
            lambdaQueryWrapper.eq(Order::getReceiverCountyId, order.getReceiverCountyId());
        }
        lambdaQueryWrapper.orderBy(true, false, Order::getOrderId);
        return page(iPage, lambdaQueryWrapper);
    }


    /**
     * 获取订单列表
     *
     * @param ids 订单id列表
     * @return
     */
    @Override
    public List<Order> findAll(List<String> ids) {
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            lambdaQueryWrapper.in(Order::getOrderId, ids);
        }
        lambdaQueryWrapper.orderBy(true, false, Order::getOrderId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 获取订单分页数据 客户端使用
     *
     * @param orderSearchDTO
     * @return
     */
    @Override
    public IPage<Order> pageLikeForCustomer(OrderSearchDTO orderSearchDTO) {

        Integer page = orderSearchDTO.getPage();
        Integer pageSize = orderSearchDTO.getPageSize();

        IPage<Order> ipage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Order> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(StringUtils.isNotEmpty(orderSearchDTO.getOrderId()), Order::getOrderId, orderSearchDTO.getOrderId());
        orderQueryWrapper.like(StringUtils.isNotEmpty(orderSearchDTO.getKeyword()), Order::getOrderId, orderSearchDTO.getKeyword());
        orderQueryWrapper.eq(StringUtils.isNotEmpty(orderSearchDTO.getMemberId()), Order::getMemberId, orderSearchDTO.getMemberId());
        orderQueryWrapper.eq(StringUtils.isNotEmpty(orderSearchDTO.getReceiverPhone()), Order::getReceiverPhone, orderSearchDTO.getReceiverPhone());
        orderQueryWrapper.orderByDesc(Order::getCreateTime);
        return page(ipage, orderQueryWrapper);
    }

    /**
     * 计算订单价格
     *
     * @param orderDTO
     * @return
     */
    @Override
    public Map calculateAmount(OrderDTO orderDTO) {
        //距离    distance
        //重量    weight
//        1、1千克以内20元
//        2、1千克以上，订单距禽在200公里以下的，首重1千克，首重价格20元，续重每1千克资费为6元

//        3、1千克以上，订单距离在200To。公里的，首重1千克，首重价格20元，续重每1千克资 费为9元
//        4、1千克以上，订单距离在500公里以上的，首重1千克，首重价格20元，续重每1千克资费为15元
        orderDTO = getDistance(orderDTO);

        if(orderDTO.getSenderAddress().equals("发件人详细地址填写错误") || orderDTO.getReceiverAddress().equals("收件人详细地址填写错误")){
            //地址有误，无法解析
            Map map =new HashMap();
            map.put("amount","0");
            map.put("errorMsg","无法计算订单和订单价格，请核对地址是否有误");
            map.put("orderDto",orderDTO);
            return map;
        }
        System.out.println("---------- ---------- ---------- ---------- --------- --------- ---------");
        KieSession session = ReloadDroolsRulesService.kieContainer.newKieSession();
//        KieSession session = kieContainer.newKieSession();
        //设置Fact对象
        AddressRule addressRule = new AddressRule();
        addressRule.setTotalWeight(orderDTO.getOrderCargoDto().getTotalWeight().doubleValue());
        addressRule.setDistance(orderDTO.getDistance().doubleValue());

        //将对象加入到工作对象
        session.insert(addressRule);

        AddressCheckResult addressCheckResult=new AddressCheckResult();
        session.insert(addressCheckResult);

        int i = session.fireAllRules();
        System.out.println("触发了"+i+"条规则");
        session.destroy();

        if(addressCheckResult.isPostCodeResult()){
            System.out.println("规则匹配成功，订单价格为："+ addressCheckResult.getResult());
            orderDTO.setAmount(new BigDecimal(addressCheckResult.getResult()));

            Map map = new HashMap();
            map.put("orderDto",orderDTO);
            map.put("amount",addressCheckResult.getResult());
            return map;
        }
        //返回总价格
        return null;
    }

    //查询所有订单-条件查询
    @Override
    public List<Order> orderlist(Order order) {
        return orderMapper.orderpage(order);
    }

    @Autowired
    private ProvincesMapper provincesMapper;
    @Override
    public List<Provinces> provincesList() {
        List<Provinces> list = provincesMapper.all();
        return list;
    }

    @Autowired
    private CitiesMapper citiesMapper;
    @Override
    public List<Cities> citiesList() {
        return citiesMapper.all();
    }

    @Autowired
    private AreasMapper areasMapper;
    @Override
    public List<Areas> areasList() {
        return areasMapper.all();
    }

    @Override
    public List<Cities> findcitiesbyid(Provinces provinces) {
        List<Cities> list = citiesMapper.findcitiesbyid(provinces);
        return list;
    }

    @Override
    public List<Areas> findareasbyid(Cities cities) {
        return areasMapper.findareasbyid(cities);
    }

    /**
     * 根据订单id查询订单详情
     * @param id
     * @return
     */
    @Override
    public Order orderInfo(String id) {
        Order info = orderMapper.orderInfo(id);
        return info;
    }

    /**
     * 调用百度地图服务接口，根据寄件人地址和收件人地址计算订单距离
     *
     * @param orderDTO
     * @return
     */
    public OrderDTO getDistance(OrderDTO orderDTO) {
        //调用百度地图服务接口，获取寄件人地址对应的坐标经纬度
        String begin = BaiduMapUtils.getCoordinate(orderDTO.getSenderAddress());
        if (begin == null) {
            orderDTO.setSenderAddress("发件人详细地址填写错误");
            return orderDTO;
        }
        //调用百度地图服务接口，获取收件人地址对应的坐标经纬度
        String end = BaiduMapUtils.getCoordinate(orderDTO.getReceiverAddress());
        if (end == null) {
            orderDTO.setReceiverAddress("收件人详细地址填写错误");
        }
        System.out.println("******************************************************************");
        System.out.println(begin+","+end);
        //调用百度地图工具类，根据寄件人地址和收件人地址坐标计算订单距离
        Double distance = BaiduMapUtils.getDistance(begin, end);
        //格式化经纬度小数点后位数
        DecimalFormat decimalFormat = new DecimalFormat("#.####");
        String distanceStr = decimalFormat.format(distance / 1000);//距离，单位/千米
        System.out.println("两地距离为："+distanceStr+"千米");
        //赋值寄件地和收件地址距离
        orderDTO.setDistance(new BigDecimal(distanceStr));
        return orderDTO;
    }


}
